import javax.swing.*;
import java.awt.event.*;
import java.io.*;

final class SaveAsItem extends AbstractAction{
  private final Doer frame;
    private JFileChooser files;

    SaveAsItem(String name,Doer frame){
    super(name);
    this.frame=frame;
    String iconFileName="images"+File.separator+name+".gif";
    if(new File(iconFileName).exists())putValue(SMALL_ICON,new ImageIcon(iconFileName));
  }

    public void actionPerformed(ActionEvent e){
      saveAsFile();
    }

    public void saveAsFile(){
      try{
        InterWindow interWindow=(InterWindow)(frame.getTab().getComponentAt(frame.getSelect()));
        files=new JFileChooser(new File(interWindow.getDirection()));
	File file=showDialog("Save As...","Save",frame.getTab().getTitleAt(frame.getSelect()),interWindow);
        if(file!=null){
	  FileWriter out=new FileWriter(file);
          JTextArea textArea=interWindow.getTextArea();
	  out.write(textArea.getText());
          out.flush();
          out.close();
	  frame.getSaveItem().setEnabled(false);
	  interWindow.setSaved(true);
	  frame.setTitle(file.getName());
	  frame.getStatusBar().getCD().setText("cd: "+interWindow.getDirection());
	  frame.getStatusBar().getSystemDirection().setText("D: "+interWindow.getDirection());
	}
      }
      catch(IOException e){
        System.out.println(e);
      }
    }

    public File showDialog(String title,String text,String fileName,InterWindow interWindow){
      files.setDialogTitle(title);
      files.setApproveButtonText(text);
      files.setFileSelectionMode(files.FILES_ONLY);
      files.setCurrentDirectory(new File(frame.getDirection()));
      files.rescanCurrentDirectory();
      files.setSelectedFile(new File(fileName));

      Ext javaFilter=new Ext(".java","Java files(*.java)");

      files.addChoosableFileFilter(javaFilter);
      files.setFileFilter(javaFilter);

      int result=files.showDialog(frame,null);

      if(result==files.APPROVE_OPTION){
        frame.getTab().setTitleAt(frame.getSelect(),files.getSelectedFile().getName());

	if(files.getSelectedFile().exists()){
          if(JOptionPane.NO_OPTION==JOptionPane.showConfirmDialog(frame,
	                                                         "Overwrite?",
								 "Confirm Save As",
	                                                         JOptionPane.YES_NO_OPTION,
		                                                 JOptionPane.WARNING_MESSAGE))return null;
        interWindow.setDirection(files.getSelectedFile().getParent());
	frame.setDirection(files.getSelectedFile().getParent());
	  return files.getSelectedFile();
	}else{
	  interWindow.setDirection(files.getSelectedFile().getParent());
	  frame.setDirection(files.getSelectedFile().getParent());
          new File(files.getSelectedFile().getParent()).mkdir();
	  return new File(files.getSelectedFile().getParent(),files.getSelectedFile().getName());
	}

      }else return null;
    }
  }
